﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace CrmCustomInstallActions.Commands
{
    class BackupConfiguration : GenericCrmSolutionCommand
    {
        internal override bool InitializeSpecificCommand()
        {
            return true;
        }

        
        public override bool ExecuteCommand(CommandModes CommandMode)
        {
            try
            {
                string f = "";
                if (CommandMode == CommandModes.Install)
                {
                    CrmSdk.ExportCompressedAllXmlRequest exportRequest = new CrmCustomInstallActions.CrmSdk.ExportCompressedAllXmlRequest();
                    f = Path.Combine(backupFolder, "systemconfiguration-" + DateTime.Now.ToString("s") + ".zip");
                    WriteLog("Backing up the XML Confifiguration to '" + f);
                    exportRequest.EmbeddedFileName = Path.Combine(backupFolder, f);
                    ReportProgress(50, "Backing up the Configuration");
                    CrmSdk.ExportCompressedXmlResponse exportResponse = (CrmSdk.ExportCompressedXmlResponse)service.Execute(exportRequest);
                    ReportProgress(100, "Configuration backup up");
                    WriteLog("Configuration backed up to the file '" + f);
                    Props.Add("CONFIGBACKUP", f);
                    return true;
                }
                else if (CommandMode == CommandModes.Rollback)
                {
                    ReportProgress(50, "Removing the backed up configuration");
                    if (!Props.ContainsKey("CONFIGBACKUP"))
                    {
                        WriteLog("The Configuration backup file could not be found in the CRM Solution Installer properties");
                        return false;
                    }
                    else
                    {
                        f = Convert.ToString(Props["CONFIGBACKUP"]);
                        File.Delete(f);
                        ReportProgress(100, "Backup deleted");
                        WriteLog("The configuration backup file '" + f + "' was deleted successfully");
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Exceptions.Add("Unexpected error occured during the Configuration backup or deletion", e.Message);
                return false;
            }

        }

        public override bool SupportsUninstall
        {
            get { return false; }
        }

        public override bool SupportsUserInterface
        {
            get { return false; }
        }
    }
}
